package cc.rengu.igas.channel.cups.core.packswitch;

import cc.rengu.igas.channel.cups.common.constant.CupsParamConstant;
import cc.rengu.igas.channel.cups.common.constant.CupsTreeNodeConstant;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.communication.MiniClientNotifyImpl;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

/**
 * @author who
 */
public class CupsGetRadpKey implements MiniClientNotifyImpl {

    /**
     * 根据7，11,32,33确定应答交易匹配的RADP_KEY
     */
    @Override
    public String getKey() {
        RgLogger rglog = RgLog.getLogger(this.getClass().getName());
        XmlTreeUtil tree = new XmlTreeUtil();
        StringBuilder buf = new StringBuilder();
        try {
            String transDateTime = tree.getXmlTreeStringValue(CupsTreeNodeConstant.CUPS_RSP_TXN_DATE_TIME);
            if (null == transDateTime) {
                rglog.error("获取银联7域失败");
                return null;
            }
            buf.append(transDateTime);
            rglog.info("{}={}", CupsTreeNodeConstant.CUPS_RSP_TXN_DATE_TIME, transDateTime);
            String cupSsn = tree.getXmlTreeStringValue(CupsTreeNodeConstant.CUPS_RSP_CUP_SN);
            if (null == cupSsn) {
                String traceNo = tree.getXmlTreeStringValue(CupsTreeNodeConstant.CUPS_RSP_CUP_TRACENO);
                if (null == traceNo) {
                    rglog.error("获取银联11域失败");
                    return null;
                } else {
                    cupSsn = traceNo;
                }

            }
            buf.append(cupSsn);

            rglog.info("{}={}", CupsTreeNodeConstant.CUPS_RSP_CUP_SN, cupSsn);
            String acqInstCode = tree.getXmlTreeStringValue(CupsTreeNodeConstant.CUPS_RSP_ACQ_INST_ID_CODE);
            if (null != acqInstCode) {
                buf.append(acqInstCode);
            }
            String fwdInstCode = tree.getXmlTreeStringValue(CupsTreeNodeConstant.CUPS_RSP_FWD_INST_ID_CODE);
            if (null != fwdInstCode) {
                buf.append(fwdInstCode);
            }
            String tunlSn = buf.toString();


            String platformId = (String) UnifiedCache.get(CupsParamConstant.CACHE_CUPS_SN, tunlSn);
            if (platformId != null) {
                UnifiedCache.remove(CupsParamConstant.CACHE_CUPS_SN, tunlSn);
                return platformId;
            } else {
                rglog.error("交易匹配不到原请求{}", tunlSn);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }
}
